import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { isURL } from '@/utils/validate'

import * as $auth from '@/utils/auth'

const _import = require('./_import_' + process.env.NODE_ENV)

Vue.use(Router)

//如登录页和首页和一些不用权限的公用页面,hidden:true是不需要显示的的
export const globalRoutes = [
	{
	    path: '/login',
	    name: 'login',
	    component: _import('login/login'),
	    meta: { keepAlive:true, title: '登录页面', icon: '' }
	},
	{ path: '/404', component: _import('errorPage/404'), name:'404', meta:{ title:'404未找到' }, hidden: true },
	{ path: '/401', component: _import('errorPage/401'), name:'401', meta:{ title:'401页面失效，需重新登录' }, hidden: true },
	{ path: '/noAccess', component: _import('errorPage/unauthorized'), name:'unauthorized', meta:{ title:'对不起，您没有权限访问该页面！' }, hidden: true },
]

// 顶级菜单路由
const baseLayoutRoutes = {
	path:'/',
	component: _import('layout/baseLayout'),
	name:'baseLayout',
	redirect:{ name:'dashboard' },
	meta:{ title:'主入口整体布局' },
	// children:[
	// 	{
	// 		path:'dashboard',
	// 		name:'dashboard',
	// 		meta: { keepAlive:true, title: '首页', icon: '', permission:[]},
	// 		component:_import('dashboard/index'),
	// 	}
	// ],
	beforeEnter (to, from, next) {
		let token = $auth.getToken()
		if(!token || !/\S/.test(token)) {
			next({
                path: '/login',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
		}
		next()
	}
}

const router = new Router({
//   mode: 'history', //后端支持可开
	mode:'hash',
	scrollBehavior: () => ({ y: 0 }),
	isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  	routes: globalRoutes
})

/**
 * 判断当前路由类型, global: 全局路由, notGlobal: 非全局路由
 * @param {*} route 当前路由
 */
function getCurrentRouteType (route,globalRoutesList) {
	let temp = [];
	if(globalRoutesList==undefined){
		globalRoutesList = globalRoutes;
	}
	for (let i = 0; i < globalRoutesList.length; i++) {
	  if (route.path === globalRoutesList[i].path) {
		return 'global'
	  } else if (globalRoutesList[i].children && globalRoutesList[i].children.length >= 1) {
		temp = temp.concat(globalRoutesList[i].children)
	  }
	}
	return temp.length >= 1 ? getCurrentRouteType(route, temp) : 'notGlobal'
}

router.beforeEach((to, from, next) => {
	console.log('%c-------进入beforeEach-------','color:green')
	// 添加动态(菜单)路由
	// 1. 已经添加 or 全局路由, 直接访问
	// 2. 获取菜单列表, 添加并保存本地存储
	if (router.options.isAddDynamicMenuRoutes || getCurrentRouteType(to) === 'global') {
		next()
	} else {
		// 若本地没有token，则直接跳转到登录页面
		let token = $auth.getToken()
		if(!token || !/\S/.test(token)) {
			next({
				path: '/login',
				query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
			})
			return;
		}
		store.dispatch('getMenuList').then(response => {
			if (response && response.code === 0) {
				let menuList = response.menuList || [];
				if(menuList.length==0){
					next({
						path: '/noAccess'
					})
					return;
				}
				let topMenuList = menuList.filter((item) => {
					return item.type === 0;
				});

				// 将二级菜单leftmenu数据存放在一级菜单topmenu的children属性下
				if(topMenuList.length>0){	// 存在一级菜单topmenu
					topMenuList = topMenuList.map((item) => {
						let arrTemp = menuList.filter((it) => {
							return  item.menuId === it.parentId && it.type!=2;
						});
						if(arrTemp.length>0){
							item.children = arrTemp
						}
						return item;
					});
					addMenuDynamicRoutes(topMenuList);

				}else{		// 没有顶部菜单,则将菜单全部放在左侧栏
					addLeftMenuDynamicRoutes(null,menuList);
				}
				let menuListArr = menuList.filter(item=>{
					return item.type!=2;
				})
				sessionStorage.setItem('menuList', JSON.stringify(menuListArr || []));
				sessionStorage.setItem('topMenuList', JSON.stringify(topMenuList));

				router.addRoutes([
				{ path: '*', redirect: { name: '404' } }
				]);

				router.options.isAddDynamicMenuRoutes = true;
				next({ ...to, replace: true })
			}else{
				sessionStorage.setItem('menuList', JSON.stringify([]));
				sessionStorage.setItem('topMenuList', JSON.stringify([]));
				next();
			}
		}).catch((e) => {
			console.log(e);
		})
	}
})

/**
 * 创建菜单路由
 * @param {*} menuItem 菜单项
 */
function createMenuRoute(menuItem){
	let route = {
		path: menuItem.url,
		// component: _import(menuItem.component),
		name: menuItem.url,
		meta: {
			keepAlive:false,
			menuId: menuItem.menuId,
			title: menuItem.name,
			isDynamic: true,
			iframeUrl: ''
		}
	}
	// url以http[s]://开头, 通过iframe展示
	if (isURL(menuItem.component)) {
		route['name'] = `i-${menuItem.menuId}`
		route['meta']['isIframe'] = true;
		route['meta']['iframeUrl'] = menuItem.component
	} else {
		try {
			if(menuItem.component){
				route['component'] = _import(`${menuItem.component}`) || null
			}else{
				console.log(menuItem.name+'component值为空');
			}

		} catch (e) {
			console.log(`${menuItem.component}`+'模块不存在');
			console.log(e);
		}
	}
	return route;
}
/**
 * 添加动态顶级(菜单)路由（无左侧菜单路由）
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addMenuDynamicRoutes(menuList = [], routes = []){
	let menuItem;
	for (let i = 0; i < menuList.length; i++) {
		menuItem = menuList[i];
	  	if (/\S/.test(menuItem.url)) {
			menuItem.url = menuItem.url.replace(/^\//, '');
			let route;
			// 存在左侧二级菜单
			if(menuItem.children && menuItem.children.length>0){
				addLeftMenuDynamicRoutes(menuItem,menuItem.children);
			}else{		// 不存在左侧菜单
				if(!menuItem.component) continue;
				routes.push(createMenuRoute(menuItem))
			}
		}else{		// 为顶部下拉菜单
			let jroute,menuItemList;
			if(menuItem.list && menuItem.list.length>0){
				menuItemList = menuItem.list;
				for (let j = 0, jlen = menuItemList.length; j < jlen; j++) {
					let jmenuItem = menuItemList[j];
					if(!jmenuItem.component) continue;
					routes.push(createMenuRoute(jmenuItem))
				}
			}
		}
	}
	// 顶部一级菜单路由
	baseLayoutRoutes.name = 'dynamic-topmenu-routes'
	baseLayoutRoutes.children = routes
	router.addRoutes([
		baseLayoutRoutes
	])
}

/**
 * 根据顶部菜单，添加动态二级菜单（左侧菜单路由）路由
 * @param {*} parentMenuItem 顶部父菜单
 * @param {*} childrenMenuList 顶部父菜单对应的左侧菜单项
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addLeftMenuDynamicRoutes(parentMenuItem, childrenMenuList, routes = []){
	let temp = [],
		pathRoot = null,
		redirectPath=null;
	let menuList = childrenMenuList || [];
	let secondLayoutRoutes = null;
	if(parentMenuItem){
		pathRoot = '/'+parentMenuItem.url;
		if(menuList.length>0){
			redirectPath = pathRoot+'/'+menuList[0].url;
		}else{
			redirectPath='/dashboard';
		}
	}else{
		pathRoot = '/'
		redirectPath='/dashboard';
		secondLayoutRoutes = baseLayoutRoutes;
	}

	secondLayoutRoutes = {
		path:pathRoot,
		component: _import('layout/index'),
		name:'secondLayout',
		meta:{ title:'二级菜单路由主入口整体布局' },
		redirect:{ path:redirectPath },
		beforeEnter (to, from, next) {
			let token = $auth.getToken()
			if(!token || !/\S/.test(token)) {
				next({
					path: '/login',
					query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
				})
			}
			next()
		}
	};
	secondLayoutRoutes.name = parentMenuItem?pathRoot:'baseRoot';

	for (let i = 0; i < menuList.length; i++) {
		if(menuList[i].type==2) continue;
		if(menuList[i].list && menuList[i].list.length >0) {
			let jroute,menuItemList;
			menuItemList = menuList[i].list;
			for (let j = 0, jlen = menuItemList.length; j < jlen; j++) {
				let jmenuItem = menuItemList[j];
				if(!jmenuItem.component) continue;
				routes.push(createMenuRoute(jmenuItem))
			}
		}else{
			if(/\S/.test(menuList[i].url)){
				menuList[i].url = menuList[i].url.replace(/^\//, '')

				if(!menuList[i].component) continue;
				routes.push(createMenuRoute(menuList[i]));
			}
		}
	}

	// 添加路由
	// if(parentMenuItem.url=='base'){
	// 	let customRoutes = [
	// 		{
	// 			path: 'entp/info/:id',
	// 			name: 'entpInfo',
	// 			meta: {title: '企业信息详情页'},
	// 			component: _import('modules/base/entp/entp-info')
	// 		},
	// 		{
	// 			path: 'vec/info/:id',
	// 			name: 'vecInfo',
	// 			meta: {title: '车辆详情页'},
	// 			component: _import('modules/base/vec/vec-info')
	// 		},
	// 		{
	// 			path: 'pers/info/:id(\\d+)',
	// 			name: 'persInfo',
	// 			meta: {title: '人员信息',},
	// 			component: _import('modules/base/pers/pers-info')
	// 		},
	// 		{
	// 			path: 'tank/info/:id(\\d+)',
	// 			name: 'tankInfo',
	// 			meta: {title: '罐体信息'},
	// 			component: _import('modules/base/tank/tank-info')
	// 		},
	// 		{
	// 			path: 'rtePlan/info/:id',
	// 			name: 'rtePlanInfo',
	// 			meta: {title: '电子路单信息'},
	// 			component: _import('modules/base/rtePlan/rtePlan-info')
	// 		},
	// 		{
	// 			path: 'ench/info/:id(\\d+)',
	// 			name: 'enchInfo',
	// 			meta: {title: '危险品信息'},
	// 			component: _import('modules/base/ench/ench-info')
	// 		},
	// 		{
	// 			path: 'passport/info/:id(\\d+)',
	// 			name: 'passportInfo',
	// 			meta: {title: '通行证信息'},
	// 			component: _import('modules/base/passport/passport-info')
	// 		},
	// 		{
	// 			path: 'chemica/info/:id',
	// 			name: 'chemicaInfo',
	// 			meta: {title: '危化品信息'},
	// 			component: _import('modules/base/chemica/chemica-info')
	// 		},
	// 		{
	// 			path: 'prodLoad/add/:id',
	// 			name: 'prodLoadAdd',
	// 			meta: {title: '企业围栏新增查看'},
	// 			component: _import('modules/base/prodLoad/prod-add')
	// 		},
	// 		{
	// 			path: 'wb/info/:id',
	// 			name: 'wbInfo',
	// 			meta: {title: '过磅数据详情'},
	// 			component: _import('modules/base/wb/wb-info')
	// 		}
	// 	]
	// 	routes = routes.concat(customRoutes);
	// }

	secondLayoutRoutes.children = routes
	router.addRoutes([
		secondLayoutRoutes
	])
	sessionStorage.setItem('dynamicLeftMenuRoutes', JSON.stringify(secondLayoutRoutes.children || '[]'))
}

export default router
